// note.js - 完整对接后端API，支持多用户、私有/公开权限

const API_BASE = '/api/v1/notes';
let notes = [];
let skip = 0;
let limit = 10;

// 获取当前登录用户id
function getUserId() {
    return localStorage.getItem('user_id');
}

// 渲染分页控件
function renderPagination(total) {
    const pagination = document.getElementById('pagination');
    if (!pagination) return;
    pagination.innerHTML = '';
    const totalPages = Math.ceil(total / limit);
    const currentPage = Math.floor(skip / limit) + 1;
    for (let i = 1; i <= totalPages; i++) {
        const btn = document.createElement('button');
        btn.textContent = i;
        btn.className = 'page-btn' + (i === currentPage ? ' active' : '');
        btn.onclick = () => {
            skip = (i - 1) * limit;
            fetchNotes();
        };
        pagination.appendChild(btn);
    }
}

// 获取笔记总数（用于分页）
async function fetchNotesCount() {
    // 假设后端有 /api/v1/notes/count?user_id=xxx
    // 如果没有，可以在 fetchNotes 后端返回总数
    // 这里用 fetchNotes 返回的 notes.length 近似处理
    return notes.length;
}

// 获取笔记列表（分页）
async function fetchNotes() {
    const user_id = getUserId();
    if (!user_id) {
        alert('请先登录！');
        window.location.href = 'login.html';
        return;
    }
    try {
        const res = await fetch(`${API_BASE}?user_id=${user_id}&skip=${skip}&limit=${limit}`);
        if (!res.ok) throw new Error('获取笔记失败');
        notes = await res.json();
        renderTable(notes);
        // 渲染分页（假设后端返回的notes.length<limit时为最后一页）
        // 这里建议后端返回总数，前端才能精确分页
        // 这里简单处理：如果第一页且数量等于limit，显示2页
        let total = skip + notes.length + (notes.length === limit ? limit : 0);
        renderPagination(total);
    } catch (e) {
        alert('加载笔记失败：' + e.message);
    }
}

function renderTable(data) {
    const tbody = document.getElementById('noteTableBody');
    tbody.innerHTML = '';
    if (!data.length) {
        const tr = document.createElement('tr');
        tr.innerHTML = `<td colspan="5" style="color:#aaa;">暂无笔记</td>`;
        tbody.appendChild(tr);
        return;
    }
    const currentUserId = getUserId();
    data.forEach(note => {
        const tr = document.createElement('tr');
        let actionBtns = '';
        // 只有本人能查看私有笔记，公开笔记所有人可查看
        if (note.is_published || (currentUserId && Number(currentUserId) === note.user_id)) {
            actionBtns += `<button class="action-btn view-btn" data-id="${note.id}">查看</button>`;
        }
        if (currentUserId && Number(currentUserId) === note.user_id) {
            actionBtns += ` <button class="action-btn edit-btn" data-id="${note.id}">修改</button>`;
            actionBtns += ` <button class="action-btn delete-btn" data-id="${note.id}">删除</button>`;
        }
        tr.innerHTML = `
            <td>${note.category || ''}</td>
            <td>${note.title || ''}</td>
            <td>${note.created_at ? new Date(note.created_at).toLocaleString() : ''}</td>
            <td>${note.is_published ? '公开' : '私有'}</td>
            <td>${actionBtns}</td>
        `;
        tbody.appendChild(tr);
    });
}

// 搜索功能（本地过滤）
function searchNotes() {
    const keyword = document.getElementById('searchInput').value.trim();
    if (!keyword) {
        renderTable(notes);
        return;
    }
    const filtered = notes.filter(note =>
        (note.category && note.category.includes(keyword)) ||
        (note.title && note.title.includes(keyword)) ||
        (note.content && note.content.includes(keyword))
    );
    renderTable(filtered);
}
document.getElementById('searchBtn').addEventListener('click', searchNotes);
document.getElementById('searchInput').addEventListener('keydown', function(e) {
    if (e.key === 'Enter') searchNotes();
});

// 查看详情弹窗（仅本人或公开可看）
async function showDetail(id) {
    try {
        const res = await fetch(`${API_BASE}/${id}`);
        if (!res.ok) throw new Error('获取详情失败');
        const note = await res.json();
        const currentUserId = getUserId();
        if (!note.is_published && Number(currentUserId) !== note.user_id) {
            alert('无权查看该私有笔记');
            return;
        }
        document.getElementById('detailTitle').textContent = note.title;
        document.getElementById('detailCategory').textContent = note.category;
        document.getElementById('detailContent').textContent = note.content;
        document.getElementById('detailCreatedAt').textContent = note.created_at ? new Date(note.created_at).toLocaleString() : '';
        document.getElementById('detailIsPublished').textContent = note.is_published ? '公开' : '私有';
        document.getElementById('noteDetailModal').style.display = 'block';
    } catch (e) {
        alert('加载详情失败：' + e.message);
    }
}
document.getElementById('closeDetailModal').onclick = function() {
    document.getElementById('noteDetailModal').style.display = 'none';
};
window.onclick = function(event) {
    if (event.target === document.getElementById('noteDetailModal')) {
        document.getElementById('noteDetailModal').style.display = 'none';
    }
};

// 事件委托：表格操作按钮

document.getElementById('noteTableBody').onclick = async function(e) {
    if (e.target.classList.contains('view-btn')) {
        showDetail(e.target.dataset.id);
    } else if (e.target.classList.contains('edit-btn')) {
        editNote(e.target.dataset.id);
    } else if (e.target.classList.contains('delete-btn')) {
        if (confirm('确定要删除这条笔记吗？')) {
            try {
                const res = await fetch(`${API_BASE}/${e.target.dataset.id}`, { method: 'DELETE' });
                if (!res.ok) throw new Error('删除失败');
                await fetchNotes();
            } catch (err) {
                alert('删除失败：' + err.message);
            }
        }
    }
};

// 添加笔记（仅本人）
function addNote() {
    const user_id = getUserId();
    if (!user_id) {
        alert('请先登录！');
        window.location.href = 'login.html';
        return;
    }
    const title = prompt('请输入标题：');
    if (!title) return;
    const category = prompt('请输入分类：');
    if (!category) return;
    const content = prompt('请输入内容：');
    if (!content) return;
    const is_published = confirm('是否公开？点击“确定”为公开，取消为私有');
    const note = { user_id: Number(user_id), title, category, content, is_published };
    fetch(API_BASE, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(note)
    })
    .then(res => {
        if (!res.ok) throw new Error('新建失败');
        return res.json();
    })
    .then(() => fetchNotes())
    .catch(e => alert('新建失败：' + e.message));
}
document.getElementById('addNoteBtn').onclick = addNote;

// 修改笔记（仅本人）
function editNote(id) {
    const note = notes.find(n => n.id == id);
    const user_id = getUserId();
    if (!note || Number(user_id) !== note.user_id) {
        alert('无权修改该笔记');
        return;
    }
    const title = prompt('修改标题：', note.title);
    if (!title) return;
    const category = prompt('修改分类：', note.category);
    if (!category) return;
    const content = prompt('修改内容：', note.content);
    if (!content) return;
    const is_published = confirm('是否公开？点击“确定”为公开，取消为私有');
    fetch(`${API_BASE}/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title, category, content, is_published })
    })
    .then(res => {
        if (!res.ok) throw new Error('修改失败');
        return res.json();
    })
    .then(() => fetchNotes())
    .catch(e => alert('修改失败：' + e.message));
}

// 新建笔记表单提交
const noteForm = document.getElementById('noteForm');
if (noteForm) {
    noteForm.onsubmit = function(e) {
        e.preventDefault();
        const user_id = getUserId();
        if (!user_id) {
            alert('请先登录！');
            window.location.href = 'login.html';
            return;
        }
        const title = document.getElementById('noteTitle').value.trim();
        const category = document.getElementById('noteCategory').value.trim();
        const content = document.getElementById('noteContent').value.trim();
        const is_published = document.getElementById('noteIsPublished').checked;
        if (!title || !category || !content) {
            alert('请填写完整');
            return;
        }
        const note = { user_id: Number(user_id), title, category, content, is_published };
        fetch(API_BASE, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(note)
        })
        .then(res => {
            if (!res.ok) throw new Error('新建失败');
            return res.json();
        })
        .then(() => {
            fetchNotes();
            noteForm.reset();
        })
        .catch(e => alert('新建失败：' + e.message));
    };
}

// 初始化
fetchNotes();
